#!/bin/bash

source config.sh

FN=`find ${JOB_FILE_DIR} -name "*.sh"`

i=0
for file in $FN
do
  j=0
  error_t=0
  HEAD=${file%%.sh}
  HEAD2=${HEAD##*/}

  APP_t2=`echo $HEAD2 | awk -F "_" 'END {print $1}'`
  THREAD_t2=`echo $HEAD2 | awk -F "_" 'END {print $6}'`
  ENERGY=`echo $HEAD2 | awk -F "_" 'END {print $2}'`
  INPUT_SAMPLE=`echo $HEAD2 | awk -F "_" 'END {print $3}'`
  INPUT_BFIELD=`echo $HEAD2 | awk -F "_" 'END {print $4}'`
  INPUT_PYLIST=`echo $HEAD2 | awk -F "_" 'END {print $5}'`

  while [ $j -lt $RUNS ]; do 
    ERROR_FILE_NAME=${OUTPUT_ERR_FILE_DIR}/${APP_t2}_${ENERGY}_${INPUT_SAMPLE}_${INPUT_BFIELD}_${INPUT_PYLIST}_${THREAD_t2}_$j.err

    # run !!
    echo -n running $file
    $file ${j} 2>> ${ERROR_FILE_NAME}


    # check if the execution has failed 
    if [ -s ${ERROR_FILE_NAME} ]; then
       echo "   [FAILURE]"
       error_t=$(expr $error_t + 1)
       tar czvf ${ERROR_FILE_NAME}.core.tar.gz core*
       # rm -f core* > /dev/null
    else
       echo "   [SUCCESS]"
       rm -f ${ERROR_FILE_NAME}
    fi


    # move outputs to the specified directory
    tar cvzf ${OUTPUT_LOG_FILE_DIR}/${HEAD2}_${j}.tar.gz Geant4MT* >& /dev/null


    # move outputs (physics value) into the specified format
    case $APP_t2 in
      ParN02 )
        echo -n ${THREAD_t2}" " > ${OUTPUT_PHY_FILE_DIR}/${HEAD2}_${j}.out 
        echo " 0" >> ${OUTPUT_PHY_FILE_DIR}/${HEAD2}_${j}.out 
        ;;
      ParN03 )

        num_t=0
        sum_t=0.0

        for vv in `grep "mean Energy in Absorber" ${OUTPUT_FILE_DIR}/${HEAD2}_${j}.out | awk {'print $6'}`
        do 
          num_t=$(expr $num_t + 1)
#          sum_t=`echo $sum_t + $vv | bc -l`
          sum_t=`$PWD/add.sh $sum_t $vv`
        done

        if [ $num_t -gt 0 ]; then
          avg_t=`echo $sum_t / $num_t | bc -l`
          echo ${THREAD_t2} $avg_t > ${OUTPUT_PHY_FILE_DIR}/${HEAD2}_${j}.out 
        fi
        ;;
      SimplifiedCalo )

        num_t=0
        sum_t=0.0

        for vv in `grep "<Etot_em>" ${OUTPUT_FILE_DIR}/${HEAD2}_${j}.out | awk {'print $6'}`
        do
          num_t=$(expr $num_t + 1)
#          sum_t=`echo $sum_t + $vv | bc -l`
          sum_t=`$PWD/add.sh $sum_t $vv`
        done

        if [ $num_t -gt 0 ]; then
          avg_t=`echo $sum_t / $num_t | bc -l`
          echo ${THREAD_t2} $avg_t >> ${OUTPUT_PHY_FILE_DIR}/${HEAD2}_${j}.out 
        fi
        ;;
    esac
 
    # save taken time  into files
    for vv in `grep "The time of experiments" ${OUTPUT_FILE_DIR}/${HEAD2}_${j}.out | awk {'print $6'} | head -c 8`
    do
      echo ${THREAD_t2} $vv >> ${OUTPUT_TIME_FILE_DIR}/${HEAD2}_${j}.out 
    done

    rm -f Geant4MT*
    i=$(expr $i + 1)
    j=$(expr $j + 1)
  done

  echo ${THREAD_t2} " " ${error_t} >> ${OUTPUT_ERR_FILE_DIR}/${APP_t2}_${ENERGY}_${INPUT_SAMPLE}_${INPUT_BFIELD}_${INPUT_PYLIST}.sum

done

echo $i "jobs have been executed"
